pub mod session;
pub mod usb;

use std::time::Duration;

use ylong_runtime::sync::error::RecvTimeoutError;
use ylong_runtime::sync::mpsc::{BoundedReceiver, BoundedSender};

use crate::common::hdc_error::{HdcError, HdcErrorKind};
use crate::common::task_message::TaskMessage;

// pub trait StubInterface {
//     fn close(&mut self) -> Result<(), HdcError>;
//     fn read(&mut self, buf: &mut [u8]) -> Result<usize, HdcError>;
//     fn write(&mut self, buf: &[u8]) -> Result<usize, HdcError>;
//     fn get_connect_key(&self) -> &str;
// }

pub struct Stub {
    wr: BoundedSender<TaskMessage>,
    rd: BoundedReceiver<TaskMessage>,
}

impl Stub {
    pub fn new(wr: BoundedSender<TaskMessage>, rd: BoundedReceiver<TaskMessage>) -> Self {
        Self { wr, rd }
    }

    pub async fn read(&mut self) -> Result<TaskMessage, HdcError> {
        self.rd.recv_timeout(Duration::from_secs(60 * 5)).await.map_err(|err| match err {
            RecvTimeoutError::Closed => {
                let msg = "session is close".to_owned();
                log::error!("{msg}");
                HdcError::new(HdcErrorKind::HdcClose, msg)
            }
            RecvTimeoutError::Timeout => {
                let msg = "recv timeout".to_owned();
                log::error!("{msg}");
                HdcError::new(HdcErrorKind::HdcTimedOut, msg)
            }
        })
    }

    pub async fn write(&mut self, msg: TaskMessage) -> Result<(), HdcError> {
        self.wr.send(msg).await.map_err(|_e| HdcError::new(HdcErrorKind::HdcOther, "send filed".to_owned()))
    }
}
